package com.example.lists;

import org.springframework.beans.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;

public class ListToMap2 {
    public static void main(String[] args) {
        List<User> list = new ArrayList<User>();
        list.add(new User(1, 1, "11"));
        list.add(new User(2, 1, "11"));
        list.add(new User(3, 5, "33"));
        list.add(new User(5, 5, "55"));
        //若要排序，指定转为双向列表 linkedHashMap ，map是无序的
        Map<Integer, List<User>> map = list.stream()
                .sorted(Comparator.comparing(User::getParentId).reversed())
                .collect(Collectors.groupingBy(User::getParentId, LinkedHashMap::new, Collectors.toList()));
        System.out.println(map);

        //遍历map推荐使用entrySet，速度比keySet快
        //entrySet
        Iterator<Map.Entry<Integer, List<User>>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<Integer, List<User>> entry = iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue();
            User use = new User();
            entry.getValue().stream().anyMatch(u -> {
                if(u.getId() == 1){
                    BeanUtils.copyProperties(u, use);
                    System.out.println(use);
                    return true;
                }
                return false;
            });
        }

        //keySet
        /*Map map = new HashMap();
        Iterator iter = map.keySet().iterator();
        while (iter.hasNext()) {
            Object key = iter.next();
            Object val = map.get(key);
        }*/
    }
}
